<template>
    <div class="main">
        <el-card class="box-card" style="margin-bottom: 10%;margin-right: 4%;">
            <template #header>
                <div class="card-header">
                    <span>登录表单</span>
                </div>
            </template>
            <el-form :model="form" label-width="80px">
                <el-form-item label="用户名">
                    <el-input v-model="form.username" />
                </el-form-item>
                <el-form-item label="密码">
                    <el-input type="password" v-model="form.password" />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="login">登录</el-button>
                    <el-button type="success" @click="register">注册</el-button>
                </el-form-item>
            </el-form>
        </el-card>

    </div>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'

const router = useRouter()

const form = ref({
    username: '',
    password: '',
})

// 登录
const login = async () => {
    const result = await $api.post('/user/login', form.value)
    const { code, data, msg } = result.data
    console.log(code, data, msg);
    // 登录成功时
    if (code == 0) {
        ElMessage.success(msg)
        localStorage.setItem('token', data.token)
        router.push('/index/player')
    } else {
        ElMessage.error(msg)
    }
}

// 注册
const register = async () => {
    const result = await $api.post('/user/register', form.value)
    const { code, data, msg } = result.data
    // 注册成功时
    if (code == 0) {
        ElMessage.success(msg)
        login()
    } else {
        ElMessage.error(msg)
    }
}
</script>

<style scoped>
.main {
    width: 100vw;
    height: 100vh;
    display: flex;
    justify-content: center;
    align-items: center;
    background-image: url('../assets/bg.png');
    background-size: 100% 100%;
}
</style>